package cn.lastjune.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.lastjune.pojo.Problem;
import cn.lastjune.service.AreaService;
import cn.lastjune.service.ProblemService;
import cn.lastjune.util.NumberUtil;
import cn.lastjune.util.Page;

@Controller
@RequestMapping("/problem")
public class ProblemController {
	@Autowired
	ProblemService problemService;
	@Autowired
	AreaService areaService;
	public String emptyJson = "{metaData:{totalProperty : 'total',root : "
			+ "'result',fields: ['eventcauseID','areaID','recID','eventsrcID','eventsrc','eventsubsrc','eventtype','bigcategory','smallcategory','subcategory','eventstate','currentstatename'"
			+ "]},total:0, result : []}";

	@RequestMapping(method = RequestMethod.GET)
	public void getAll(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		PrintWriter out = response.getWriter();
		int start = request.getParameter("start") == null ? 0 : NumberUtil
				.parseInt(request.getParameter("start"));
		int limit = request.getParameter("limit") == null ? 11 : NumberUtil
				.parseInt(request.getParameter("limit"));
		final Page<Problem> page = new Page<Problem>();
		page.setPageNo(start / limit + 1);
		page.setPageSize(limit);
		final Page<Problem> result = problemService.getAll(page);
		final List<Problem> list = result.getResult();
		StringBuilder sb = new StringBuilder();
		int count = list.size();
		String sbnew;
		if (count > 0) {
			String jsonHead = "{"
					+ "metaData:{"
					+ "totalProperty : 'total',"
					+ "root : 'result',"
					+ "fields: ['eventcauseID','areaID','recID','eventsrcID','eventsrc','eventsubsrc','eventtype','bigcategory','smallcategory','subcategory','eventstate','currentstatename']},"
					+ "total:" + result.getTotalCount() + ", result : [";
			sb.append(jsonHead);

			for (Problem e : list) {
				count--;
				sb.append("{" + "eventcauseID : '"
						+ e.getEventcauseid().toString() + "'," + "areaID : '"
						+ e.getArea().getAreaid() + "'," + "recID: '"
						+ e.getRecid() + "'," + "eventsrcID: '"
						+ e.getEventsrcid() + "',eventsrc:'" + e.getEventsrc()
						+ "',eventsubsrc:'" + e.getEventsubsrc()
						+ "',eventtype:'" + e.getEventtype() + "',"
						+ "bigcategory:'" + e.getBigcategory()
						+ "',smallcategory:'" + e.getSmallcategory() + "',"
						+ "subcategory:'" + e.getSubcategory()
						+ "',eventstate:'" + e.getEventstate()
						+ "',currentstatename:'" + e.getCurrentstatename()
						+ "'}");
				if (count > 0) {
					sb.append(",");
				}
			}
			sb.append("]}");
			sbnew = sb.toString().replace("null", "");
			System.out.println(sbnew);
		} else {
			sbnew = sb.append(emptyJson).toString();
		}
		out.print(sbnew);
		out.flush();
	}

	@RequestMapping(method = RequestMethod.POST)
	public void modifyProblem(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		response.setHeader("Charset", "UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json"); // 解决后台数据中文乱码
		response.setCharacterEncoding("UTF-8");
		String method = request.getParameter("method");
		Problem e = new Problem();
		if ("add".equals(method) || "delete".equals(method)
				|| "edit".equals(method)) {
			String problemID = request.getParameter("eventcauseID");
			String areaID = request.getParameter("areaID");
			String eventsrcID = request.getParameter("eventsrcID");
			String eventsrc = request.getParameter("eventsrc");
			String eventsubsrc = request.getParameter("eventsubsrc");
			String eventtype = request.getParameter("eventtype");
			String bigcategory = request.getParameter("bigcategory");
			String smallcategory = request.getParameter("smallcategory");
			String subcategory = request.getParameter("subcategory");
			String currentstatename = request.getParameter("currentstatename");
			String eventstate = request.getParameter("eventstate");
			String recID=request.getParameter("recID");
			BigDecimal recIDT=new BigDecimal(0);
			if(recID!=null){
				recIDT=new BigDecimal(recID);
			}
			e.setEventcauseid(problemID);
			if (areaID != null) {
				e.setArea(areaService.getAreaById(areaID));
			}
			e.setEventsrcid(new BigDecimal(eventsrcID));
			e.setEventsrc(eventsrc);
			e.setEventsubsrc(eventsubsrc);
			e.setBigcategory(bigcategory);
			e.setSmallcategory(smallcategory);
			e.setEventtype(eventtype);
			e.setSubcategory(subcategory);
			e.setCurrentstatename(currentstatename);
			e.setEventstate(eventstate);
			e.setRecid(recIDT);
		}

		System.out.println(method);
		if ("add".equals(method)) {
			try {
				problemService.insertProblem(e);
				out.print("{success:true,msg:\'yes\'}");
				out.flush();
				return;
			} catch (Exception e2) {
				out.print("{success:false,msg:\'no\'},{failure:true}");
				out.flush();
				return;
			}

		}
		if ("edit".equals(method)) {
			try {
				problemService.updateProblem(e);
				out.print("{success:true,msg:\'yes\'}");
				out.flush();
				return;
			} catch (Exception e2) {
				out.print("{success:false,msg:\'no\'},{failure:true}");
				out.flush();
				return;
			}
		}
		if ("delete".equals(method)) {
			try {
				String ids[] = request.getParameterValues("ids");
				for (String id : ids) {
					problemService.deleteProblem(id);
				}
				out.print("{success:true,msg:\'yes\'}");
				out.flush();
				return;
			} catch (Exception e2) {
				out.print("{success:false,msg:\'no\'},{failure:true}");
				out.flush();
				return;
			}
		}
		if ("search".equals(method)) {
			try {
				int start = request.getParameter("start") == null ? 0
						: NumberUtil.parseInt(request.getParameter("start"));
				int limit = request.getParameter("limit") == null ? 11
						: NumberUtil.parseInt(request.getParameter("limit"));
				String search = request.getParameter("detail") == null ? ""
						: request.getParameter("detail").toString();
				String type = request.getParameter("searchType") == null ? ""
						: request.getParameter("searchType").toString();
				System.out.println(search);
				final Page<Problem> page = new Page<Problem>();
				page.setPageNo(start / limit + 1);
				page.setPageSize(limit);
				final List<Problem> result = problemService.getAllFilter(type,
						search);
				StringBuilder sb = new StringBuilder();
				int count = result.size();
				String sbnew;
				if (count > 0) {
					String jsonHead = "{"
							+ "metaData:{"
							+ "totalProperty : 'total',"
							+ "root : 'result',"
							+ "fields: ['eventcauseID','areaID','recID','eventsrcID','eventsrc','eventsubsrc','eventtype','bigcategory','smallcategory','subcategory','eventstate','currentstatename']},"
							+ "total:" + result.size() + ", result : [";
					sb.append(jsonHead);

					for (Problem e2 : result) {
						count--;
						sb.append("{" + "eventcauseID : '"
								+ e2.getEventcauseid().toString() + "',"
								+ "areaID : '" + e2.getArea().getAreaid()
								+ "'," + "recID: '" + e2.getRecid() + "',"
								+ "eventsrcID: '" + e2.getEventsrcid()
								+ "',eventsrc:'" + e2.getEventsrc()
								+ "',eventsubsrc:'" + e2.getEventsubsrc()
								+ "',smallcategory:'" + e2.getSmallcategory()
								+ "'," + "subcategory:'" + e2.getSubcategory()
								+ "',eventtype:'" + e2.getEventtype() + "',"
								+ "bigcategory:'" + e2.getBigcategory()
								+ "',eventstate:'" + e2.getEventstate()
								+ "',currentstatename:'"
								+ e2.getCurrentstatename() + "'}");
						if (count > 0) {
							sb.append(",");
						}
					}
					sb.append("]}");
					sbnew = sb.toString().replace("null", "");
					System.out.println(sbnew);
				} else {
					sbnew = sb.append(emptyJson).toString();
				}
				out.print(sbnew);
				out.flush();
			} catch (Exception e2) {
				out.print("{success:false,msg:\'no\'},{failure:true}");
				out.flush();
				e2.printStackTrace();
				return;
			}
		}
	}

}
